<template>
  <ContentContainer
    :show-pagination="false"
    :show-footer="false"
    :refresh="false">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      layout="vertical"
      scroll-to-first-error>
      <div class="weight-label">缓存配置</div>
      <div class="normal-label">首页缓存</div>
      <span class="sub-label">
        指定首页内容的缓存过期时间，提升首页访问性能。
      </span>

      <a-checkbox
        v-model="form.cache_config.index_cache_enable"
        class="my-6 w-fit"
        @change="handleIndexCacheEnableChange"
        >启用</a-checkbox
      >
      <a-form-item
        v-if="form.cache_config.index_cache_enable"
        field="cache_config.index_cache_time"
        label="过期时间"
        hide-asterisk
        asterisk-position="end"
        required>
        <section class="w-100 cloud-diverse-select">
          <a-input-number
            v-model="form.cache_config.index_cache_time!"
            :precision="0"
            :min="1"
            :max="form.index_cache_unit === 'd' ? 365 : 99999"
            placeholder="请输入"
            class="!h-8">
            <template #append>
              <a-select
                v-model="form.index_cache_unit"
                class="!w-78px"
                :options="cacheTimeOptions">
              </a-select>
            </template>
          </a-input-number>
        </section>
      </a-form-item>
      <a-divider type="dashed" class="!mt-0 !mb-6" />
      <div class="normal-label">缓存规则</div>
      <div class="sub-label mb-2">
        指定资源内容的缓存过期时间，有效提升资源的命中率，提升访问性能，减少回源。
      </div>
      <a-form-item hide-label>
        <cache-rule-table
          ref="cacheRuleTableRef"
          v-model:list="form.cache_config.suffix_cache_rule">
        </cache-rule-table>
      </a-form-item>

      <section class="flex flex-col mb-6">
        <a-checkbox
          v-model="form.cache_config.ignore_query_string"
          class="!leading-22px w-fit"
          >忽略查询字符串</a-checkbox
        >
        <span class="sub-label">
          忽略查询字符串，向所有用户提供相同的资源。示例：example.com/example.jpg?ignore=this-query-string
        </span>
      </section>
      <a-form-item>
        <section class="flex flex-col">
          <span class="normal-label">浏览器缓存 TTL</span>
          <span class="sub-label">
            用于配置资源在浏览器中的缓存时长，可降低回源率。
          </span>
          <a-radio-group
            v-model="form.cache_config.browser_cache_enable"
            class="my-2"
            @change="handleBrowserCacheEnableChange">
            <a-radio :value="false">遵循源站</a-radio>
            <a-radio :value="true">自定义</a-radio>
          </a-radio-group>
          <a-form-item
            v-if="form.cache_config.browser_cache_enable"
            field="cache_config.browser_cache_time"
            hide-asterisk
            hide-label
            class="!w-100 flex items-center cloud-diverse-select"
            required>
            <a-input-number
              v-model="form.cache_config.browser_cache_time!"
              :min="1"
              :max="form.browser_cache_unit === 'd' ? 365 : 99999"
              :precision="0"
              :default-value="10"
              placeholder="请输入">
            </a-input-number>
            <a-select
              v-model="form.browser_cache_unit"
              :options="cacheTimeOptions"
              class="time-unit-select"
              @change="
                () => formRef.resetFields(['cache_config.browser_cache_time'])
              ">
            </a-select>
          </a-form-item>
        </section>
      </a-form-item>
    </a-form>
    <a-button
      type="primary"
      class="my-6"
      :loading="saveLoading"
      @click="handleSave"
      >保存配置</a-button
    >
  </ContentContainer>
</template>
<script lang="ts" setup>
import {
  getApiSiteCacheConfigApi,
  updateApiSiteCacheConfigApi
} from '@/apis/modules/site/site'
import CacheRuleTable from '@/views/site/components/CacheRuleTable/CacheRuleTable.vue'
import type { FieldRule } from '@arco-design/web-vue/es/form'
import { cloneDeep } from 'lodash-es'
const route = useRoute()
const formRef = ref()
const cacheRuleTableRef = ref<InstanceType<typeof CacheRuleTable>>()
const form = ref({
  index_cache_unit: A_CACHE_TIME.HOUR,
  browser_cache_unit: A_CACHE_TIME.SECOND,
  cache_config: {
    browser_cache_enable: false,
    browser_cache_time: 10,
    ignore_query_string: false,
    index_cache_enable: false,
    index_cache_time: 10,
    suffix_cache_rule: [{ suffix: '', cache_time: 1, cache_unit: 'd' }] as any[]
  }
})

const rules = computed<Record<string, FieldRule[]>>(() => {
  return {
    'cache_config.browser_cache_time': [
      { required: true, message: '请输入浏览器缓存时间' }
    ],
    'cache_config.index_cache_time': [
      { required: true, message: '请输入过期时间' }
    ],
    region_id: [{ required: true, message: '请选择区域' }],
    protocol: [{ required: true, message: '请选择回源协议' }],
    host: [
      { required: true, message: '请输入自定义域名' },
      { validator: validateDomain }
    ]
  }
})
const handleIndexCacheEnableChange = (val: boolean) => {
  if (val) {
    form.value.cache_config.index_cache_time = 10
    form.value.index_cache_unit = A_CACHE_TIME.HOUR
  }
}
const handleBrowserCacheEnableChange = (val: boolean) => {
  if (val) {
    form.value.cache_config.browser_cache_time = 10
    form.value.browser_cache_unit = A_CACHE_TIME.MINUTE
  }
}

const id = computed(() => route.params.id as string)
//缓存配置
const { request } = useRequest(getApiSiteCacheConfigApi, {
  auto: true,
  params: { id: id.value },
  success: (res) => {
    Object.assign(form.value, res)
    if (!res!.cache_config!.browser_cache_time) {
      form.value.cache_config.browser_cache_time = 10
      form.value.browser_cache_unit = A_CACHE_TIME.MINUTE
    } else {
      const browserCacheData = separateNumberAndLetter(
        res!.cache_config!.browser_cache_time!
      )
      form.value.cache_config.browser_cache_time =
        +browserCacheData.value as any
      form.value.browser_cache_unit = browserCacheData.unit! as any
    }
    if (!res!.cache_config!.index_cache_time!) {
      form.value.cache_config.index_cache_time = 10
      form.value.index_cache_unit = A_CACHE_TIME.HOUR
    } else {
      const indexCacheData = separateNumberAndLetter(
        res!.cache_config!.index_cache_time!
      )
      form.value.cache_config.index_cache_time = +indexCacheData.value as any
      form.value.index_cache_unit = indexCacheData.unit! as any
    }
    form.value.cache_config.suffix_cache_rule.forEach((item) => {
      if (item.suffix.length) {
        item.suffix = item.suffix.join(',')
        const cacheData = separateNumberAndLetter(item.cache_time)
        item.cache_time = Number(cacheData.value)
        item.cache_unit = cacheData.unit
      } else {
        item.cache_time = 60
        item.suffix = ''
        item.cache_unit = 's'
      }
    })
  }
})
const saveLoading = ref(false)
//缓存配置保存
const handleSave = async () => {
  const err = await formRef.value?.validate()
  const err1 = await cacheRuleTableRef.value?.validateFn()
  if (err || !err1) return
  saveLoading.value = true
  const data = cloneDeep({
    ...form.value,
    id: id.value
  })
  if (!form.value.cache_config.browser_cache_enable) {
    data.cache_config.browser_cache_time = undefined
  } else {
    data.cache_config.browser_cache_time = ((data.cache_config
      .browser_cache_time || 10) + data.browser_cache_unit) as any
  }
  if (!form.value.cache_config.index_cache_enable) {
    data.cache_config.index_cache_time = undefined
  } else {
    data.cache_config.index_cache_time = ((data.cache_config.index_cache_time ||
      10) + data.index_cache_unit) as any
  }
  data.cache_config.suffix_cache_rule.forEach((item) => {
    item.suffix = item.suffix?.split(',') ?? []
    item.cache_time = item.cache_time + item.cache_unit
    delete item.cache_unit
  })
  await updateApiSiteCacheConfigApi({ ...data })
    .then(() => {
      ToastUtils.success('操作成功')
      request()
    })
    .finally(() => (saveLoading.value = false))
}

watchEffect(() => {
  // request({ id: id.value })
})
</script>

<style lang="less" scoped>
:deep(.arco-select-view-single) {
  .arco-select-view-suffix {
    padding-left: 4px;
  }
}
.weight-label {
  @apply text-sm/22px font-700 text-1 mb-6;
}
.normal-label {
  @apply text-sm/22px text-2;
}
.sub-label {
  @apply text-xs/5 text-5;
}
</style>
